﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using shfa.snomtastic.admin.components;
using shfa.snomtastic.data.business;
using shfa.snomtastic.data.ip;
using Telerik.Web.UI;

namespace shfa.snomtastic.admin.editcontrols
{
    public partial class eSubnet : EditBase
    {

        #region Public Members

        public bool IsNewItem
        {
            get { return (ActiveItemId == Guid.Empty); }
        }


        public Guid ActiveItemId
        {
            get { return (hfItemId.Value != string.Empty) ? new Guid(hfItemId.Value) : Guid.Empty; }
            set { hfItemId.Value = value.ToString(); }
        }

        #endregion

        #region Page

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Page_Init(object sender, EventArgs e)
        {
            if (ItemId!=Guid.Empty)
                ActiveItemId = ItemId;

            if (ActiveItemId != Guid.Empty)
            {
                bindItem();
            }
            else
            {
                bindConfigurationList(new Guid());
            }
          
        }

        #endregion

        #region Helpers

        private void bindItem()
        {
            SubnetController sc = new SubnetController();
            SubnetInfo si = sc.SelectSubnet(ActiveItemId);
            if (si != null)
            {
                lblHeaderRight.Text = si.IP + " - " + si.Mask;

                txtIP.Text = si.IP;
                bindSubnets(si.Mask);
                txtIPStart.Text = si.StartIP;
                txtIPEnd.Text = si.EndIP;
                bindConfigurationList(si.ConfigurationId);
            }


        }


        private void bindSubnets(string mask)
        {
            IPTool ip = new IPTool(txtIP.Text);

            ddMasks.Items.Clear();

            if (ip.getNetworkClassPrefix() == -1)
            {
                ddMasks.Items.Add(new RadComboBoxItem(""));

            }
            else
            {
                int startPrefix = ip.getNetworkClassPrefix();
                // first is Networkclass
                ddMasks.Items.Add(new RadComboBoxItem(ip.getNetworkMaskByPrefix(startPrefix)));
                startPrefix++;
                if (!ip.isFirstSubNetBit()) startPrefix++;

                for (int i = startPrefix; i <= 30; i++)
                    ddMasks.Items.Add(new RadComboBoxItem((ip.getNetworkMaskByPrefix(i))));
            }
            if (mask != string.Empty)
            {
                if (ddMasks.FindItemByText(mask)!=null)
                {
                    ddMasks.FindItemByText(mask).Selected = true;
                }
            
            }

        }

        private void bindConfigurationList(Guid id)
        {
            // Configurations
            ConfigurationController cc = new ConfigurationController();
            List<ConfigurationInfo> ciList = cc.SelectConfigurations("Name Asc");
            ddConfigurations.DataSource = ciList;
            ddConfigurations.DataTextField = "Name";
            ddConfigurations.DataValueField = "ConfigurationId";
            ddConfigurations.DataBind();
            ddConfigurations.Items.Insert(0, new RadComboBoxItem("<None>", Guid.Empty.ToString()));
            if (id != Guid.Empty & ddConfigurations.Items.FindItemByValue(id.ToString()) != null)
                ddConfigurations.Items.FindItemByValue(id.ToString()).Selected = true;


        }

        #endregion


        #region Action Event Helpers


        private void SaveItem()
        {
            if (Page.IsValid)
            {
                SubnetController sc = new SubnetController();
                SubnetInfo si = new SubnetInfo();

                // IPTool
                IPTool ip = GetIPTool(txtIP.Text, ddMasks.SelectedIndex);
                string[] ipRange = ip.getNetworkIPRange();

                if (!IsNewItem)
                    si = sc.SelectSubnet(ActiveItemId);
                    

                si.IP = txtIP.Text;
                si.Mask = ddMasks.SelectedItem.Text;
                si.StartIP = ipRange[0];
                si.EndIP = ipRange[1];
                si.StartInt = (Int32)ip.IPAddressToNumber(ipRange[0]);
                si.EndInt = (Int32)ip.IPAddressToNumber(ipRange[1]);

                si.ConfigurationId = new Guid(ddConfigurations.SelectedValue);

                if (IsNewItem)
                    sc.InsertSubnet(si);

                else
                    sc.UpdateSubnet(si);
                    
                RaiseNavEvent(this, new NavEventArgs("eSubnets", ActiveItemId));
            }


        }


        private void DeleteItem()
        {
            SubnetController sc = new SubnetController();
            sc.DeleteSubnet(ActiveItemId);
            RaiseNavEvent(this, new NavEventArgs("eSubnets", ActiveItemId));
        }


        #endregion

        #region Helpers

        private IPTool GetIPTool(string ipAddress, int maskIndex)
        {
            // IPTool
            IPTool ip = new IPTool(ipAddress);
            if (maskIndex > 0)
            {
                int select = maskIndex;
                int prefix = select + ip.getNetworkClassPrefix();
                if (select != 0 && !ip.isFirstSubNetBit()) prefix++;
                ip.setNetworkPrefix(prefix);
            }

            return ip;
        }

        #endregion



        #region EditBase
        public override void EditBase_ActionEvent(object sender, ActionClickArgs e)
        {
            switch (e.ActionName)
            {
                case "Save":
                    SaveItem();
                    break;
                case "Delete":
                    DeleteItem();
                    break;
                case "Return":
                    RaiseNavEvent(this, new NavEventArgs("eSubnets", ActiveItemId));
                    break;
                default:
                    break;
            }

        }

        public override List<ActionInfo> ActionList
        {
            get
            {
                List<ActionInfo> al = new List<ActionInfo>();
                al.Add(new ActionInfo("Save", "Save Subnet", "~/images/icons/save.png", "", true, true));
                al.Add(new ActionInfo("Delete", "Delete Subnet", "~/images/icons/delete.png", "Are you sure you want to delete this subnet", !IsNewItem));
                al.Add(new ActionInfo("Return", "Return", "~/images/icons/undo.png"));
                return al;

            }
        }

        #endregion

        protected void txtIP_TextChanged(object sender, EventArgs e)
        {
            bindSubnets(string.Empty);
            IPTool ip = GetIPTool(txtIP.Text, ddMasks.SelectedIndex);
            string[] ipRange = ip.getNetworkIPRange();
            txtIPStart.Text = ipRange[0];
            txtIPEnd.Text = ipRange[1];

        }

        protected void ddMasks_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            IPTool ip = GetIPTool(txtIP.Text, ddMasks.SelectedIndex);
            string[] ipRange = ip.getNetworkIPRange();
            txtIPStart.Text = ipRange[0];
            txtIPEnd.Text = ipRange[1];
        }
    }
}